package avicit.bdp.dgs.mdm.service;

import avicit.bdp.dgs.mdm.dto.MdmMetricDTO;
import avicit.bdp.dgs.mdm.utils.constants.Constants;
import avicit.bdp.dgs.mdm.utils.enums.DataState;
import avicit.platform6.commons.utils.StringUtils;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @金航数码科技有限责任公司
 * @作者：developer
 * @邮箱：developer@avic-digital.com
 * @创建时间： 2023-12-14
 * @类说明：MdmMetricService
 * @修改记录：
 * @注意事项：
 * @主要功能：指标统计Service
 */
@Service
public class MdmMetricService {
    private static final Logger logger = LoggerFactory.getLogger(CommonService.class);

    @Autowired
    private TopicService topicService;

    @Autowired
    private MdmLogService mdmLogService;

    /**
     * 查看基本指标，包括主题总量、数据总量、已分发数据总量
     *
     * @return
     */
    public Map<String, Object> queryBasicMetrics() {
        Map<String, Object> result = new HashMap<>();

        // step1:统计主题总数
        Long topicNum = this.topicService.countTopic();
        result.put(Constants.METRIC_TOPIC_NUM, topicNum == null ? 0 : topicNum);

        // step2:统计数据总量
        Long dataNum = this.mdmLogService.countData();
        result.put(Constants.METRIC_MDM_DATA_NUM, dataNum == null ? 0 : dataNum);

        // step3:统计已分发数据总量
        Long distributedDataNum = this.mdmLogService.countDistributedData();
        result.put(Constants.METRIC_DISTRIBUTED_MDM_DATA_NUM, distributedDataNum == null ? 0 : distributedDataNum);

        return result;
    }

    /**
     * 根据状态统计数据总量
     *
     * @return
     */
    public List<Map<String, Object>> queryDataDistribution() {
        List<Map<String, Object>> resultList = new ArrayList<>();

        List<MdmMetricDTO> metricList = this.mdmLogService.countDataByStatus();

        if (CollectionUtils.isNotEmpty(metricList)) {
            for (MdmMetricDTO metric : metricList) {
                Map<String, Object> map = new HashMap<>();
                String statusCode = metric.getName();
                if (StringUtils.isEmpty(statusCode)) {
                    continue;
                }

                map.put("name", DataState.getDescByCode(Integer.parseInt(statusCode)));
                map.put("value", metric.getValue());
                resultList.add(map);
            }
        }

        return resultList;
    }

    /**
     * 查看24h/7d/30d新增数据趋势图
     *
     * @param timeMode,时间，0：近24h、1：近7天、2：近30天、3：本月
     * @return
     */
    public List<Map<String, Object>> queryDataTrend(Integer timeMode) {
        List<Map<String, Object>> resultList = new ArrayList<>();

        List<MdmMetricDTO> queryList = null;
        String currTime = new SimpleDateFormat(Constants.YYYY_MM_DD_HH_MM_SS).format(new Date());
        switch (timeMode) {
            case 0:
                queryList = this.mdmLogService.getLast24hAddData(buildMetricQeuryCond(currTime));
                break;
            case 1:
                queryList = this.mdmLogService.getLast7DaysAddData();
                break;
            case 2:
                queryList = this.mdmLogService.getLast30DaysAddData();
                break;
            default:
                throw new RuntimeException("不支持当前类型，timeMode：" + timeMode);
        }

        if (CollectionUtils.isNotEmpty(queryList)) {
            for (MdmMetricDTO metric : queryList) {
                Map<String, Object> map = new HashMap<>();
                map.put("name", metric.getName());
                map.put("value", metric.getValue());
                resultList.add(map);
            }
        }

        return resultList;
    }

    /**
     * 构建指标查询条件
     * 注意：
     * 1、当前仅支持24h查询条件
     *
     * @return
     */
    private List<MdmMetricDTO> buildMetricQeuryCond(String endTime) {
        List<MdmMetricDTO> condList = new ArrayList<>();

        SimpleDateFormat sdf = new SimpleDateFormat(Constants.YYYY_MM_DD_HH_MM_SS);
        Date currDate = null;
        try {
            currDate = sdf.parse(endTime);
        } catch (Exception e) {
            logger.error("查询指标失败，errMsg：", e);
        }

        Date startTime = null;
        for (int i = 23; i >= 0; i--) {
            startTime = new Date(currDate.getTime() - Constants.HOUR_MILLS);

            MdmMetricDTO cond = new MdmMetricDTO();
            cond.setStartTime(startTime);
            cond.setEndTime(currDate);
            condList.add(cond);

            currDate = startTime;
        }

        return condList;
    }
}
